import parseAttrString from "./parseAttrString.js";

export default function(str){
    var index = 0
    var rest = ""
    var startRegExp = /^\<([a-z]+[1-6]?)(\s[^\<]+)?\>/;
    var endRegExp = /^\<\/([a-z]+[1-6]?)\>/;
    var wordRegExp = /^([^\<]+)\<\/[a-z]+[1-6]?\>/;
    var stack1 = [];
    var stack2 = [{children:[]}];
    while(index<str.length-1){
        rest = str.substring(index);
        if(startRegExp.test(rest)){
            let tag = rest.match(startRegExp)[1];
            let attrsString =rest.match(startRegExp)[2];
            let attrs = parseAttrString(attrsString)
            stack1.push(tag)
            stack2.push({
                tag,
                "children":[],
                attrs
            })
            const attrsLength = attrsString!=null?attrsString.length:0
            // <> 
            index += tag.length + 2 + attrsLength;
        }else if(endRegExp.test(rest)){
            let tag = rest.match(endRegExp)[1];
            let pop_tag = stack1.pop();
            let pop_arr = stack2.pop();
            if(tag === pop_tag){
                if( stack2.length>0){
                    stack2[stack2.length-1].children.push(pop_arr)
                }
            }
            //  </>
            index += tag.length + 3;
        }else if(wordRegExp.test(rest)){
            //识别文字，并且不能是全空
            let word = rest.match(wordRegExp)[1]
            if( !/^\s+$/.test(word))
            {
                stack2[stack2.length-1].children.push({
                    'text':word,
                    "type":3
                })
            }
            index += word.length;
        }
        else{
            //标签中文字
            index++;
        }
    }
    return stack2[0];
}